local M = {}

function M.createKernel()
	local kernel = {}

	kernel.category = "filter"
	kernel.name = "roll"
	kernel.isTimeDependent = true
	kernel.vertexData = 
	{
		{
			name = "speed", 
			default = 0.1, 
			min = 0, 
			max = 1, 
			index = 0, -- This corresponds to "CoronaVertexUserData.x"
		}, 
		{
			name = "offset", 
			default = 0, 
			index = 1, -- This corresponds to "CoronaVertexUserData.y"
		}, 
		{
			name = "time", 
			default = -1, 
			index = 2, -- This corresponds to "CoronaVertexUserData.z"
		}, 
	}
	kernel.fragment = 
	[[
		P_COLOR vec4 FragmentKernel( P_UV vec2 texCoord )
		{	
			P_DEFAULT float time;
			if (CoronaVertexUserData.z==-1.0)
			{
				time = CoronaTotalTime;
			}
			else
			{
				time = CoronaVertexUserData.z;
			}
			P_DEFAULT vec2 uv = vec2(texCoord.x, mod(texCoord.y-time*CoronaVertexUserData.x, 1.0));
			P_DEFAULT vec4 texColor = texture2D( CoronaSampler0, uv);
			return CoronaColorScale(texColor);
		}
	]]
	return kernel
end

function M.init()
	local kernel = M.createKernel()
	graphics.defineEffect(kernel)
end

M.init()

function M.test()
	local kernel = M.createKernel()
	local effect = graphics.defineEffect(kernel)
	-- local img = display.newImage("assets/bg/bg_main.png")

	-- layout.setXY(img, SCREEN_CX, SCREEN_CY)

	-- img.fill.effect = "filter.custom." .. kernel.name


	local paint = {
		type = 'composite',
		paint1 = {type = "image", filename = "assets/scene/run_shader/img_grass.jpg"}, 
		paint2 = {type = "image", filename = "assets/scene/run_shader/img_grass.jpg"},
	}
	local ground = display.newRect(SCREEN_CX,SCREEN_CY,0,1500)
	ground.anchorY = 0
	ground.fill = paint
	ground.fill.effect = "filter.custom.roll"
	ground.fill.effect.speed = 0.03
	ground.fill.effect.time = 0
	-- local ground = display.newImageRect("assets/bg/img_grass.jpg", 8000, 1500)
	-- ground.anchorY = 0
	-- layout.setXY(ground, SCREEN_CX,SCREEN_CY)
	-- ground.fill.effect = "filter.custom.roll"
	-- ground.fill.effect.speed = 0.03

	function ground:setWidth(width)
		self.width = width
		self.path.x1 = self.path.x1+(width-750)/2
		self.path.x4 = self.path.x4-(width-750)/2
	end
	-- function ground:setOffset(o)
	-- 	self.fill.effect.offset = o
	-- end	
	ground:setWidth(6000)

	-- timer.performWithDelay(1000, function()
	-- 	ground.fill.effect.time = 0
	-- end)

	local time1 = system.getTimer()

	Runtime:addEventListener("enterFrame", function()
		ground.fill.effect.time = (system.getTimer() - time1)/1000
	end)

	return ground
end

return M